//
//  KY_AppDelegate.m
//  ShaQueVideo
//
//  Created by huliang on 13-4-24.
//  Copyright (c) 2013年 科悦信达. All rights reserved.
//

#import "KY_AppDelegate.h"
#import "KY_MainViewController.h"
#import "SinaWeibo.h"
#import "KY_WeiBoActionSheet.h"
#import "KY_MyFavViewController.h"
#import "KY_ViewHistoryViewController.h"
#import "KY_MoreViewController.h"

@implementation KY_AppDelegate
@synthesize tabBarController;
@synthesize sinaweibo;
 
- (void)dealloc
{
    self.tabBarController = nil;
    [sinaweibo release];
    [_window release];
    [_mainViewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [MobClick startWithAppkey:@"5178de9756240bdfb0000ca6"];
    
    sinaweibo = [[SinaWeibo alloc] initWithAppKey:kAppKey appSecret:kAppSecret appRedirectURI:kAppRedirectURI andDelegate:self];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *sinaweiboInfo = [defaults objectForKey:@"SinaWeiboAuthData"];
    if ([sinaweiboInfo objectForKey:@"AccessTokenKey"] && [sinaweiboInfo objectForKey:@"ExpirationDateKey"] && [sinaweiboInfo objectForKey:@"UserIDKey"])
    {
        sinaweibo.accessToken = [sinaweiboInfo objectForKey:@"AccessTokenKey"];
        sinaweibo.expirationDate = [sinaweiboInfo objectForKey:@"ExpirationDateKey"];
        sinaweibo.userID = [sinaweiboInfo objectForKey:@"UserIDKey"];
    }
    
    [WXApi registerApp:@"wxf34ec3e5444eefdc"];

    NSString *pushString = [[NSUserDefaults standardUserDefaults] objectForKey:@"localpush"];
    if (!pushString) {
        
        pushString = @"1";
        [[NSUserDefaults standardUserDefaults] setObject:pushString forKey:@"localpush"];
        [[NSUserDefaults standardUserDefaults] synchronize];
                //设置10秒之后
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];//分配内存，用以存放日期格式
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//定义格式
        NSString * locationString = [formatter stringFromDate:[NSDate date]];
        NSArray *m_array = [locationString componentsSeparatedByString:@" "];
        NSString *fiveString = [NSString stringWithFormat:@"%@ 17:14:00",[m_array objectAtIndex:0]];
        
        NSDateFormatter * m_formatter = [[NSDateFormatter alloc]init];
        [m_formatter setDateStyle:NSDateFormatterMediumStyle];
        [m_formatter setTimeStyle:NSDateFormatterShortStyle];
        [m_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
         NSDate * date = [m_formatter dateFromString:fiveString];//把字符串转换成Date格式

        UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
        
        if (notification != nil) {
            // 设置推送时间
            notification.fireDate = date;
            // 设置时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            // 设置重复间隔
            notification.repeatInterval = kCFCalendarUnitDay;
            // 推送声音
            notification.soundName = UILocalNotificationDefaultSoundName;
            // 推送内容
            notification.alertBody = @"傻缺视频有更新,搞笑瞬间不容错过!";
            //显示在icon上的红色圈中的数子
            notification.applicationIconBadgeNumber += 1;
            //设置userinfo 方便在之后需要撤销的时候使用
            NSDictionary *info = [NSDictionary dictionaryWithObject:@"name"forKey:@"key"];
            notification.userInfo = info;
            //添加推送到UIApplication
            UIApplication *app = [UIApplication sharedApplication];
            [app scheduleLocalNotification:notification]; 
            
        }
    }

    NSArray *favouriteArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"favourite"];
    if (!favouriteArray) {

        [[NSUserDefaults standardUserDefaults] setObject:[NSArray array] forKey:@"favourite"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    }

    NSArray *historyArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"history"];
    if (!historyArray) {

        [[NSUserDefaults standardUserDefaults] setObject:[NSArray array] forKey:@"history"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    NSDictionary *timeDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"newTime"];
    if (!timeDic) {
      
        NSDate *date = [NSDate date];
        NSTimeInterval time = [date timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%f",time];
        
        timeDic = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"14",timeString,@"13",timeString,@"15",timeString,@"16",timeString,@"17",timeString,@"18",nil];

        [[NSUserDefaults standardUserDefaults] setObject:timeDic forKey:@"newTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    NSDictionary *updateDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"update"];
    if (!updateDic) {

    updateDic = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"14",@"0",@"13",@"0",@"15",@"0",@"16",@"0",@"17",@"0",@"18",nil];
        
        [[NSUserDefaults standardUserDefaults] setObject:updateDic forKey:@"update"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    
    self.tabBarController =[[UITabBarController alloc] init];

    //-------------------- 首页 --------------------//
    self.mainViewController = [[KY_MainViewController alloc] initWithNibName:@"KY_MainViewController" bundle:nil];
    [self.mainViewController.view setBackgroundColor:GLOBAL_VIEW_BG_COLOR];
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:self.mainViewController];
    [self.mainViewController release];

    UITabBarItem *tabBarItem;
    tabBarItem = [[UITabBarItem alloc] initWithTitle:@"傻缺视频" image:[UIImage imageNamed:@"index_normal.png"] tag:1];
    [tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"index_selected.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"index_normal.png"]];
     nav1.tabBarItem = tabBarItem;

   [self setNavBgImgAndFont:nav1 bgImgStr:@"top_nav" fontColor:GLOBAL_FONT_COLOR];
    [tabBarItem release];
    
    //-------------------- 我的收藏 --------------------//
    KY_MyFavViewController *favView = [[KY_MyFavViewController alloc] initWithNibName:@"KY_MyFavViewController" bundle:nil];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:favView];
    [favView release];
    tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的收藏" image:[UIImage imageNamed:@"fav"] tag:1];
    nav2.tabBarItem = tabBarItem;
   [self setNavBgImgAndFont:nav2 bgImgStr:@"top_nav" fontColor:GLOBAL_FONT_COLOR];
    [tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"fav_selected"] withFinishedUnselectedImage:[UIImage imageNamed:@"fav"]];
    [tabBarItem release];
    
    //-------------------- 播放纪录 --------------------//
    KY_ViewHistoryViewController *historyView = [[KY_ViewHistoryViewController alloc] initWithNibName:@"KY_ViewHistoryViewController" bundle:nil];
    UINavigationController *nav3 = [[UINavigationController alloc] initWithRootViewController:historyView];
    [historyView release];
    tabBarItem = [[UITabBarItem alloc] initWithTitle:@"播放纪录" image:[UIImage imageNamed:@"history"] tag:1];
    nav3.tabBarItem = tabBarItem;
   [self setNavBgImgAndFont:nav3 bgImgStr:@"top_nav" fontColor:GLOBAL_FONT_COLOR];
    [tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"history_selected"] withFinishedUnselectedImage:[UIImage imageNamed:@"history"]];
    [tabBarItem release];
    
    //-------------------- 更多应用 --------------------//
    KY_MoreViewController *moreView = [[KY_MoreViewController alloc] initWithNibName:@"KY_MoreViewController" bundle:nil];
    UINavigationController *nav4 = [[UINavigationController alloc] initWithRootViewController:moreView];
    [moreView release];
    tabBarItem = [[UITabBarItem alloc] initWithTitle:@"更多..." image:[UIImage imageNamed:@"more"] tag:1];
    nav4.tabBarItem = tabBarItem;
  [self setNavBgImgAndFont:nav4 bgImgStr:@"top_nav" fontColor:GLOBAL_FONT_COLOR];

    [tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"more_selected"] withFinishedUnselectedImage:[UIImage imageNamed:@"more"]];
    [tabBarItem release];
    
    //     ------------- 不锁屏 -------------//
    UIApplication* myapp = [UIApplication sharedApplication];
    myapp.idleTimerDisabled = YES;

    
    tabBarController.viewControllers = [NSArray arrayWithObjects:nav1,nav2,nav3,nav4,nil];
    [nav1 release];
    
    //     -------------自定义tabbar样式-------------//
    UIImage* tabBarBackground = [UIImage imageNamed:@"bottom_bg"];
    [[UITabBar appearance] setBackgroundImage:tabBarBackground];
    [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"tabbar_selected"]];
    //tabbarcontroller background image
    self.tabBarController.view.backgroundColor = GLOBAL_VIEW_BG_COLOR;
    self.tabBarController.tabBar.opaque = YES;
    self.tabBarController.tabBar.tintColor = [UIColor redColor];
    
    self.window.rootViewController = tabBarController;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
    
    [self.window makeKeyAndVisible];
    [tabBarController release];
    
    
    
    return YES;
}

//=======================  设置navigation的样式，背景和文字颜色 Start =============//

-(void)setNavBgImgAndFont:(UINavigationController *)nav bgImgStr:(NSString *)imgName fontColor:(UIColor *)color{
    
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    UIImage *backgroundImage = [UIImage imageNamed:imgName];  //获取图片
    if(systemVersion>=5.0)
    {
        CGSize titleSize = nav.navigationBar.bounds.size;  //获取Navigation Bar的位置和大小
        backgroundImage = [self scaleToSize:backgroundImage size:titleSize];//设置图片的大小与Navigation Bar相同
        [nav.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];  //设置背景
    }
    else
    {
        [nav.navigationBar insertSubview:[[[UIImageView alloc] initWithImage:backgroundImage] autorelease] atIndex:1];
    }
    
    
    
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      color, UITextAttributeTextColor,
      [UIFont fontWithName:@"ArialMT" size:17.0], UITextAttributeFont,
      nil]];
    
    [[UINavigationBar appearance] setTitleVerticalPositionAdjustment:5 forBarMetrics:UIBarMetricsDefault];
    [nav.navigationBar setBackgroundColor:[UIColor grayColor]];
}

//调整图片大小
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
//=======================  设置navigation的样式，背景和文字颜色 End =============//


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {

        if (resp.errCode == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil
                                                           delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];

        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败" message:nil
                                                           delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        }

    }
    else if([resp isKindOfClass:[SendAuthResp class]])
    {
        NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
        NSString *strMsg = [NSString stringWithFormat:@"Auth结果:%d", resp.errCode];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];

    }
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if (!self.sinaOrWeixin) {

        return [self.sinaweibo handleOpenURL:url];
    }
    else
    {
        return  [WXApi handleOpenURL:url delegate:self];
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (!self.sinaOrWeixin) {

        return [self.sinaweibo handleOpenURL:url];
    }
    else
    {
        return  [WXApi handleOpenURL:url delegate:self];
    }
}




@end
